# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-04 23:29
# File     : api_client.py
# Project  : codebuddy_craft
# Desc     : API客户端
# frontend/utils/api_client.py
import aiohttp
import json
from typing import Dict, Any, Optional, List


class APIClient:
    """API客户端"""
    
    def __init__(self):
        self.base_url = "http://localhost:8000"  # 后端API地址
        self.session = None
        self.headers = {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    
    async def _get_session(self) -> aiohttp.ClientSession:
        """获取HTTP会话"""
        if self.session is None or self.session.closed:
            self.session = aiohttp.ClientSession(
                headers=self.headers,
                timeout=aiohttp.ClientTimeout(total=30)
            )
        return self.session
    
    async def _request(
        self, 
        method: str, 
        endpoint: str, 
        data: Optional[Dict[str, Any]] = None,
        params: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """发送HTTP请求"""
        
        session = await self._get_session()
        url = f"{self.base_url}{endpoint}"
        
        try:
            async with session.request(
                method=method,
                url=url,
                json=data if data else None,
                params=params if params else None
            ) as response:
                
                response_data = await response.json()
                
                if response.status == 200:
                    return response_data
                else:
                    return {
                        "code": response.status,
                        "msg": response_data.get("detail", {}).get("msg", "请求失败"),
                        "data": None
                    }
        
        except Exception as e:
            return {
                "code": 50000,
                "msg": f"网络请求失败: {str(e)}",
                "data": None
            }
    
    # 项目相关API
    async def create_project(self, project_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建项目"""
        return await self._request("POST", "/api/projects", data=project_data)
    
    async def get_projects(self, page: int = 1, size: int = 10) -> Dict[str, Any]:
        """获取项目列表"""
        params = {"page": page, "size": size}
        return await self._request("GET", "/api/projects", params=params)
    
    async def get_project(self, project_id: str) -> Dict[str, Any]:
        """获取项目详情"""
        return await self._request("GET", f"/api/projects/{project_id}")
    
    async def export_project(self, project_id: str) -> Dict[str, Any]:
        """导出项目"""
        return await self._request("GET", f"/api/projects/{project_id}/export/zip")
    
    async def get_file_tree(self, project_id: str) -> Dict[str, Any]:
        """获取文件树"""
        return await self._request("GET", f"/api/projects/{project_id}/files")
    
    # 文件相关API
    async def create_file(self, project_id: str, file_data: Dict[str, Any]) -> Dict[str, Any]:
        """创建文件"""
        return await self._request("POST", f"/api/projects/{project_id}/files", data=file_data)
    
    async def get_file_content(self, file_id: str) -> Dict[str, Any]:
        """获取文件内容"""
        return await self._request("GET", f"/api/files/{file_id}")
    
    async def save_file(self, file_id: str, content: str) -> Dict[str, Any]:
        """保存文件"""
        return await self._request("PUT", f"/api/files/{file_id}", data={"content": content})
    
    async def delete_file(self, file_id: str) -> Dict[str, Any]:
        """删除文件"""
        return await self._request("DELETE", f"/api/files/{file_id}")
    
    # 代码相关API
    async def generate_code(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """生成代码"""
        return await self._request("POST", "/api/code/generate", data=request_data)
    
    async def get_completion(
        self, 
        file_id: str, 
        line: int, 
        column: int, 
        context: Optional[str] = None,
        language: str = "python"
    ) -> Dict[str, Any]:
        """获取智能补全"""
        params = {
            "file_id": file_id,
            "line": line,
            "column": column,
            "language": language
        }
        if context:
            params["context"] = context
        
        return await self._request("GET", "/api/code/completion", params=params)
    
    async def analyze_code(self, request_data: Dict[str, Any]) -> Dict[str, Any]:
        """分析代码"""
        return await self._request("POST", "/api/code/analyze", data=request_data)
    
    async def translate_code(
        self, 
        code: str, 
        source_language: str, 
        target_language: str
    ) -> Dict[str, Any]:
        """翻译代码"""
        return await self._request("POST", "/api/code/translate", data={
            "code": code,
            "source_language": source_language,
            "target_language": target_language
        })
    
    async def check_syntax(self, code: str, language: str) -> Dict[str, Any]:
        """检查语法"""
        return await self._request("POST", "/api/code/check/syntax", data={
            "code": code,
            "language": language
        })
    
    async def format_code(self, code: str, language: str = "python") -> Dict[str, Any]:
        """格式化代码"""
        params = {"code": code, "language": language}
        return await self._request("POST", "/api/code/format", params=params)
    
    async def generate_comment(
        self, 
        code: str, 
        language: str = "python", 
        style: str = "detailed"
    ) -> Dict[str, Any]:
        """生成注释"""
        params = {"code": code, "language": language, "style": style}
        return await self._request("POST", "/api/code/comment/generate", params=params)
    
    async def close(self):
        """关闭客户端会话"""
        if self.session and not self.session.closed:
            await self.session.close()
